package com.wdb007.venus.svc.biz.user;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wdb.exchange.constant.EventEnum;
import com.wdb.exchange.model.WxUserRelationRpcModel;
import com.wdb007.venus.svc.biz.manager.AlipayClientManager;
import com.wdb007.venus.svc.biz.manager.ConfigInfoManager;
import com.wdb007.venus.svc.biz.manager.IntersystemCommunicationManager;
import com.wdb007.venus.svc.biz.manager.OssUploadManager;
import com.wdb007.venus.svc.biz.manager.SmsSendManager;
import com.wdb007.venus.svc.biz.qrcode.utils.ImageMergeUtil;
import com.wdb007.venus.svc.biz.qrcode.utils.QRCodeUtil;
import com.wdb007.venus.svc.biz.utils.ArrayUtil;
import com.wdb007.venus.svc.biz.utils.DateFormatUtil;
import com.wdb007.venus.svc.biz.utils.DateUtil;
import com.wdb007.venus.svc.biz.utils.DesUtils;
import com.wdb007.venus.svc.biz.utils.MD5Util;
import com.wdb007.venus.svc.biz.utils.PhoneFormatCheckUtils;
import com.wdb007.venus.svc.biz.utils.WdbEncrypt;
import com.wdb007.venus.svc.biz.utils.WdbEncryptException;
import com.wdb007.venus.svc.dal.account.dao.AccountCashDAO;
import com.wdb007.venus.svc.dal.account.dao.AccountCashLogDAO;
import com.wdb007.venus.svc.dal.account.dao.AccountCreditDAO;
import com.wdb007.venus.svc.dal.account.dao.AccountCreditLogDAO;
import com.wdb007.venus.svc.dal.account.model.AccountCashDO;
import com.wdb007.venus.svc.dal.account.model.AccountCashLogDO;
import com.wdb007.venus.svc.dal.account.model.AccountCreditDO;
import com.wdb007.venus.svc.dal.account.model.AccountCreditLogDO;
import com.wdb007.venus.svc.dal.book.dao.BookGridDAO;
import com.wdb007.venus.svc.dal.book.dao.BookGridTransDAO;
import com.wdb007.venus.svc.dal.book.dao.BookShelfDAO;
import com.wdb007.venus.svc.dal.book.dao.GridMaintainLogDAO;
import com.wdb007.venus.svc.dal.book.dao.ReadTitleMappingDAO;
import com.wdb007.venus.svc.dal.book.model.BookGridDO;
import com.wdb007.venus.svc.dal.book.model.BookGridTransDO;
import com.wdb007.venus.svc.dal.book.model.BookShelfDO;
import com.wdb007.venus.svc.dal.book.model.BorrowingBookDO;
import com.wdb007.venus.svc.dal.book.model.BorrowingBookQueryDO;
import com.wdb007.venus.svc.dal.book.model.GridCodeAndBorrowDateDO;
import com.wdb007.venus.svc.dal.book.model.GridMaintainLogDO;
import com.wdb007.venus.svc.dal.book.model.ReadTitleMappingDO;
import com.wdb007.venus.svc.dal.order.dao.OrderTransDAO;
import com.wdb007.venus.svc.dal.qrcode.dao.QrCodePoliciesLogDAO;
import com.wdb007.venus.svc.dal.qrcode.model.QrCodePoliciesLogDO;
import com.wdb007.venus.svc.dal.user.dao.DeviceVersionDAO;
import com.wdb007.venus.svc.dal.user.dao.SmsVerificationLogDAO;
import com.wdb007.venus.svc.dal.user.dao.UserAccessLogDAO;
import com.wdb007.venus.svc.dal.user.dao.UserActivetraceDAO;
import com.wdb007.venus.svc.dal.user.dao.UserAttachmentInfoDAO;
import com.wdb007.venus.svc.dal.user.dao.UserChargeLogDAO;
import com.wdb007.venus.svc.dal.user.dao.UserCostFlagDAO;
import com.wdb007.venus.svc.dal.user.dao.UserEntiretyDAO;
import com.wdb007.venus.svc.dal.user.dao.UserEquipmentDAO;
import com.wdb007.venus.svc.dal.user.dao.UserFamilyMemberDAO;
import com.wdb007.venus.svc.dal.user.dao.UserFeedbackDAO;
import com.wdb007.venus.svc.dal.user.dao.UserInfoDAO;
import com.wdb007.venus.svc.dal.user.dao.UserInviterRelationDAO;
import com.wdb007.venus.svc.dal.user.dao.UserPointDAO;
import com.wdb007.venus.svc.dal.user.dao.UserPointLogDAO;
import com.wdb007.venus.svc.dal.user.dao.UserReadStatisticsDAO;
import com.wdb007.venus.svc.dal.user.dao.UserTokenDAO;
import com.wdb007.venus.svc.dal.user.dao.UserWishListDAO;
import com.wdb007.venus.svc.dal.user.dao.UserZhimaCreditDAO;
import com.wdb007.venus.svc.dal.user.dao.WxUserRelationDAO;
import com.wdb007.venus.svc.dal.user.model.DeviceVersionDO;
import com.wdb007.venus.svc.dal.user.model.SmsVerificationLogDO;
import com.wdb007.venus.svc.dal.user.model.UserAccessLogDO;
import com.wdb007.venus.svc.dal.user.model.UserActivetraceDO;
import com.wdb007.venus.svc.dal.user.model.UserAttachmentInfoDO;
import com.wdb007.venus.svc.dal.user.model.UserChargeLogDO;
import com.wdb007.venus.svc.dal.user.model.UserCostFlagDO;
import com.wdb007.venus.svc.dal.user.model.UserEntiretyDO;
import com.wdb007.venus.svc.dal.user.model.UserEquipmentDO;
import com.wdb007.venus.svc.dal.user.model.UserFamilyMemberDO;
import com.wdb007.venus.svc.dal.user.model.UserFeedbackDO;
import com.wdb007.venus.svc.dal.user.model.UserInfoDO;
import com.wdb007.venus.svc.dal.user.model.UserInviterRelationDO;
import com.wdb007.venus.svc.dal.user.model.UserPointDO;
import com.wdb007.venus.svc.dal.user.model.UserPointLogDO;
import com.wdb007.venus.svc.dal.user.model.UserRankInfoDO;
import com.wdb007.venus.svc.dal.user.model.UserRankInfoPageQueryDO;
import com.wdb007.venus.svc.dal.user.model.UserReadStatisticsDO;
import com.wdb007.venus.svc.dal.user.model.UserTokenDO;
import com.wdb007.venus.svc.dal.user.model.UserWishListDO;
import com.wdb007.venus.svc.dal.user.model.UserZhimaCreditDO;
import com.wdb007.venus.svc.dal.user.model.WeekReadRankDO;
import com.wdb007.venus.svc.dal.user.model.WishInfoDO;
import com.wdb007.venus.svc.dal.user.model.WishInfoPageQueryDO;
import com.wdb007.venus.svc.dal.user.model.WxUserRelationDO;
import com.wdb007.venus.svc.dal.vip.dao.VipMemberDAO;
import com.wdb007.venus.svc.dal.vip.model.VipMemberDO;
import com.wdb007.venus.svc.facade.AccountCashService;
import com.wdb007.venus.svc.facade.BookgridService;
import com.wdb007.venus.svc.facade.BsAlarmService;
import com.wdb007.venus.svc.facade.UserService;
import com.wdb007.venus.svc.facade.WxAPPMessagePushService;
import com.wdb007.venus.svc.facade.book.model.BRBookDTO;
import com.wdb007.venus.svc.facade.book.model.BorrowingBook;
import com.wdb007.venus.svc.facade.book.model.BorrowingBookDTO;
import com.wdb007.venus.svc.facade.bs.model.BsAlarmDTO;
import com.wdb007.venus.svc.facade.charge.model.WxUserRelationDTO;
import com.wdb007.venus.svc.facade.constant.BizConstants;
import com.wdb007.venus.svc.facade.constant.RspCodeEnum;
import com.wdb007.venus.svc.facade.exception.BizException;
import com.wdb007.venus.svc.facade.model.VenusSvcResp;
import com.wdb007.venus.svc.facade.user.model.DeviceUpgradeFlagDTO;
import com.wdb007.venus.svc.facade.user.model.ImgVerifacationDTO;
import com.wdb007.venus.svc.facade.user.model.RankListPageQueryDTO;
import com.wdb007.venus.svc.facade.user.model.RankListPageResultDTO;
import com.wdb007.venus.svc.facade.user.model.ReportAbnormalDTO;
import com.wdb007.venus.svc.facade.user.model.SmsVerifactionDTO;
import com.wdb007.venus.svc.facade.user.model.UserAccessLogDTO;
import com.wdb007.venus.svc.facade.user.model.UserActiveDTO;
import com.wdb007.venus.svc.facade.user.model.UserDespositCashStatusDTO;
import com.wdb007.venus.svc.facade.user.model.UserEntiretyDTO;
import com.wdb007.venus.svc.facade.user.model.UserFamilyMemberDTO;
import com.wdb007.venus.svc.facade.user.model.UserInfoAndOpenIdDTO;
import com.wdb007.venus.svc.facade.user.model.UserInfoDTO;
import com.wdb007.venus.svc.facade.user.model.UserInviteInfoDTO;
import com.wdb007.venus.svc.facade.user.model.UserLastestInfoDTO;
import com.wdb007.venus.svc.facade.user.model.UserQueryDTO;
import com.wdb007.venus.svc.facade.user.model.UserRankDTO;
import com.wdb007.venus.svc.facade.user.model.WeekRankInfoDTO;
import com.wdb007.venus.svc.facade.user.model.WishListDTO;
import com.wdb007.venus.svc.facade.user.model.WishListPageQueryDTO;
import com.wdb007.venus.svc.facade.user.model.WishListPageResultDTO;
import com.wdb007.venus.svc.facade.user.model.WishListResultDTO;
@Service("userService")
public class UserServiceImpl implements UserService {
	
	private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
	@Autowired
	private SmsVerificationLogDAO SmsVerificationLogDAO ;
	
	@Autowired
	private UserInfoDAO userInfoDAO;
	
	@Autowired 
	private UserChargeLogDAO userChargeLogDAO;
	
	@Autowired
	private AccountCreditDAO accountCreditDAO;
	
	@Autowired
	private AccountCreditLogDAO accountCreditLogDAO;
	
	@Autowired
	private AccountCashDAO accountCashDAO ;
	
	@Autowired
	private AccountCashLogDAO accountCashLogDAO ;
	
	@Autowired
	private OrderTransDAO orderTransDAO;
	
	@Autowired
	private BookGridTransDAO bookGridTransDAO;
	
	@Autowired
	private BookGridDAO bookGridDAO;
	
	@Autowired
	private GridMaintainLogDAO gridMaintainLogDAO;
	
	@Autowired
	private SmsSendManager smsSendManager ;
	
	@Autowired
	private UserFeedbackDAO userFeedbackDAO;
	
	@Autowired
	private UserAccessLogDAO userAccessLogDAO;
	
	@Autowired
	private BookgridService bookgridService;
	
	@Autowired
	private UserActivetraceDAO userActivetraceDAO;
	
	@Autowired
	private UserEquipmentDAO userEquipmentDAO;
	
	@Autowired
	private UserWishListDAO userWishListDAO;
	
	@Autowired
	private UserEntiretyDAO userEntiretyDAO;
	
	@Autowired
	private UserCostFlagDAO userCostFlagDAO;
	
	@Autowired
	private BookShelfDAO bookShelfDAO;
	
	@Autowired
	private DeviceVersionDAO deviceVersionDAO;
	
	@Autowired
	private OssUploadManager ossUploadManager;
	
	@Autowired
	private UserPointDAO userPointDAO;
	
	@Autowired
	private UserPointLogDAO userPointLogDAO;
	
	@Autowired
	private UserFamilyMemberDAO userFamilyMemberDAO;
	
	@Autowired
	private UserAttachmentInfoDAO userAttachmentInfoDAO;
	
	@Autowired
	private VipMemberDAO vipMemberDAO;
	
	@Autowired
	private UserInviterRelationDAO userInviterRelationDAO;
	
	@Autowired
	private WxUserRelationDAO wxUserRelationDAO;
	
	@Autowired
	private QrCodePoliciesLogDAO qrCodePoliciesLogDAO;
	@Autowired
	private UserTokenDAO userTokenDAO;

	@Autowired
	private WxAPPMessagePushService wxAPPMessagePushService;
	
	@Autowired
	private UserReadStatisticsDAO userReadStatisticsDAO;
	
	@Autowired
	private ReadTitleMappingDAO readTitleMappingDAO;
	
	@Autowired
	private ConfigInfoManager configInfoManager;
	
	@Autowired
	private BsAlarmService bsAlarmService;
	
	@Autowired
	private AccountCashService accountCashService;
	
	@Autowired
	private IntersystemCommunicationManager intersystemCommunicationManager;
	@Autowired
	private UserZhimaCreditDAO userZhimaCreditDAO;
	@Autowired
	private AlipayClientManager alipayClientManager;
	
	@Override
	public ImgVerifacationDTO getValidateImg()  throws BizException{
		return null;
	}

	
	@Override
	public int getRegisterCode(SmsVerifactionDTO smsVerifaction, String version) throws BizException{
		logger.info("获取验证码service调用,请求参数:{}", JSON.toJSONString(smsVerifaction));
		//1.校验手机号码是否合法
		String mobileNo = smsVerifaction.getMobileNo();
		int result = 0;
		if(!PhoneFormatCheckUtils.isPhoneLegal(mobileNo)) {
			result = 1 ;
			return result;
		}
		//2.获得六位数字验证码
		String mobile = configInfoManager.getValue("login_default_mobile");
		String[] mobileArr = mobile.split(",");
		String default_pwd = configInfoManager.getValue("login_default_pwd");
		String code = null;
		
		if(ArrayUtil.contains(mobileArr, mobileNo)) {
			code = default_pwd;
		}else {
			code = generateRegisterCode();
		}
		
		
		if(!ObjectUtils.isEmpty(version)) {
			code = code.substring(0, 4);
		}
		logger.info("生成四位或六位验证码: {}" , code);
		smsVerifaction.setSmsCode(code);
		//3.发送验证码
		boolean sendSuccess = smsSendManager.sendMessage(smsVerifaction.getMobileNo(), code);
		if(!sendSuccess) {
			result = 2 ;
			return result;
		}
		//4.保存数据
		SmsVerificationLogDO smsVerificationLogDO = new SmsVerificationLogDO();
		smsVerificationLogDO.setMobileNo(smsVerifaction.getMobileNo());
		smsVerificationLogDO.setStatus(BizConstants.SMS_STATUS_0);
		SmsVerificationLogDO queryResult = SmsVerificationLogDAO.getByMobileNo(smsVerificationLogDO);
		if(queryResult == null) {
			smsVerificationLogDO.setType(0);
			smsVerificationLogDO.setVerificationCode(code);
			smsVerificationLogDO.setVerificationCount(0);
			smsVerificationLogDO.setCreateTime(new Date());
			SmsVerificationLogDAO.insert(smsVerificationLogDO);
		}else {
			queryResult.setVerificationCode(code);
			queryResult.setVerificationCount(0);
			queryResult.setCreateTime(new Date());
			SmsVerificationLogDAO.update(queryResult);
		}
		return result;
	}

	@Override
	public String generateRegisterCode()  throws BizException{
		String code = "";
		Random random = new Random();
		for(int i=0; i<6; i++) {
			code += random.nextInt(9);
		}
		return code;
	}

	@Override
	public void sendRegisterCode(SmsVerifactionDTO smsVerifaction)  throws BizException{
		
	}

	
	
	
	@Override
	public VenusSvcResp<UserEntiretyDTO> login(SmsVerifactionDTO smsVerifaction, UserAccessLogDTO accessLog, String wxUserRelationId)  throws BizException{
	
		VenusSvcResp<UserEntiretyDTO> resp = new VenusSvcResp<UserEntiretyDTO>();
		
		//1.查询验证码是否正确
		SmsVerificationLogDO smsVerificationLogDO = new SmsVerificationLogDO();
		smsVerificationLogDO.setMobileNo(smsVerifaction.getMobileNo());
		smsVerificationLogDO.setStatus(BizConstants.SMS_STATUS_0);
		SmsVerificationLogDO queryResult = SmsVerificationLogDAO.getByMobileNo(smsVerificationLogDO);
		if(null == queryResult) {
			resp = new VenusSvcResp<UserEntiretyDTO>(RspCodeEnum.VERIFY_CODE_IS_INVALID);
			return resp ;
		}
		if(queryResult.getVerificationCount() >= 5) {	//校验次数超过5次，需要重新获取验证码
			resp = new VenusSvcResp<UserEntiretyDTO>(RspCodeEnum.VERIFY_CODE_FIVE_TIMES);
			return resp ;
		}
		
		queryResult.setVerificationCount(queryResult.getVerificationCount() + 1);
		boolean isRight = queryResult.getVerificationCode().equals(smsVerifaction.getSmsCode()) ;
		if(isRight) {
			queryResult.setStatus(BizConstants.SMS_STATUS_1);
			queryResult.setModifyTime(new Date());
		}
		
		//增加ios 和 安卓 默认用户名和密码
		String mobile = configInfoManager.getValue("login_default_mobile");
		String[] mobileArr = mobile.split(",");
		String default_pwd = configInfoManager.getValue("login_default_pwd");
		if(ArrayUtil.contains(mobileArr, smsVerifaction.getMobileNo()) && (default_pwd.equals(smsVerifaction.getSmsCode()) || default_pwd.substring(0, 4).equals(smsVerifaction.getSmsCode()))) {
			queryResult.setStatus(BizConstants.SMS_STATUS_0);
			queryResult.setModifyTime(new Date());
			queryResult.setVerificationCount(1);
		}
		SmsVerificationLogDAO.update(queryResult);
		if(!isRight) {
			resp = new VenusSvcResp<UserEntiretyDTO>(RspCodeEnum.VERIFY_CODE_IS_WRONG);
			return resp ;
		}
		String mobileNo = smsVerifaction.getMobileNo();
		String visitorIdStr = smsVerifaction.getVisitorId();
		String registrationId = smsVerifaction.getRegistration_id();
		
		resp = loginWithoutVerifaction(registrationId,visitorIdStr, mobileNo,accessLog,wxUserRelationId);
		return resp;
	}
	
	/**
	 * 注册
	 * @param mobile 手机号
	 * @param registrationId
	 * @param visitorIdStr 推荐者id
	 * @param accessLog 登入日志
	 * @param unionid 微信unionid
	 * @param deposit_amount 充值押金
	 * @param init_credit_value 初始积分
	 * @param register_gift 注册礼品
	 * @return
	 * @throws BizException
	 */
	public  VenusSvcResp<UserEntiretyDTO> registerNewUser(String mobile, String registrationId,
			String visitorIdStr, UserAccessLogDTO accessLog, WxUserRelationDTO recordDTO, 
			String deposit_amount, String init_credit_value,
			String register_gift) throws BizException{

		VenusSvcResp<UserEntiretyDTO> resp = new VenusSvcResp<UserEntiretyDTO>();
		int flag = -1;
		UserInfoDO userInfo = userInfoDAO.getByMobileNo(mobile);
		UserInfoDO userInfoDO = new UserInfoDO();
		if(null != userInfo) {
			userInfoDO.setId(userInfo.getId());
		}
		//未注册,则直接进行注册,并返回对象
		userInfoDO.setMobileNo(mobile);
		userInfoDO.setCreateTime(new Date());
		userInfoDO.setModifyTime(new Date());
		userInfoDO.setUserType(0);
		String usertoken = MD5Util.generateToken();
		userInfoDO.setUsertoken(usertoken);
		userInfoDO.setTokenGenerateTime(new Date());
		String mobileNo = mobile;
		userInfoDO.setUserName(mobileNo.substring(0, 3) + "****" + mobileNo.substring(7));
		userInfoDO.setImgurl(configInfoManager.getValue("head_img_default"));
		userInfoDO.setStatus(BizConstants.USER_INFO_STATUS_0);
		userInfoDO.setRegistrationId(registrationId);
		if(null != userInfo) {
			userInfoDAO.update(userInfoDO);
		}else {
			userInfoDAO.insert(userInfoDO);
		}
		
		
		//=============添加user_token信息=============//
		UserTokenDO userTokenDO = new UserTokenDO();
		Byte channel = BizConstants.CHANNEL_APP;
		if(!ObjectUtils.isEmpty(accessLog.getPartner()) && accessLog.getPartner().equals("wx_app")) {
			channel = BizConstants.CHANNEL_WX;
		}
		userTokenDO.setChannel(channel);
		userTokenDO.setUserId(userInfoDO.getId());
		userTokenDO.setToken(usertoken);
		if(userTokenDAO.selectByUserIdAndChannel(userTokenDO) != null ) {
			userTokenDAO.updateByUserIdAndChannel(userTokenDO);
			
		}else {
			userTokenDO.setId(UUID.randomUUID().toString().replace("-", ""));
			userTokenDAO.insert(userTokenDO);
		}
		//=============添加user_token end================//
		UserFamilyMemberDO umf = new UserFamilyMemberDO();
		umf.setImgurl(configInfoManager.getValue("head_img_default"));
		umf.setMemberType(0);
		umf.setUserName(mobileNo.substring(0, 3) + "****" + mobileNo.substring(7));
		umf.setUserId(userInfoDO.getId());
		umf.setMobileNo(mobileNo);
		umf.setCreateTime(new Date());
		userFamilyMemberDAO.save(umf);
		//创建用户信用分表,以及信用分记录表
		AccountCreditDO accountCreditDO = new AccountCreditDO();
		accountCreditDO.setUserId(userInfoDO.getId());
		Integer creditValue = null ;
		
		if(null != init_credit_value) {
			creditValue = Integer.parseInt(init_credit_value);
		}else {
			creditValue = 100;	//默认值:100
		}
		accountCreditDO.setCreditValue(creditValue);	//默认值:100
		accountCreditDO.setCreateTime(new Date());
		accountCreditDAO.insert(accountCreditDO);
		
		AccountCreditLogDO accountCreditLogDO = new AccountCreditLogDO();
		accountCreditLogDO.setAccountCreditId(accountCreditDO.getId());
		accountCreditLogDO.setChangeType(BizConstants.ACCOUNT_CREDIT_CHANGE_TYPE_10); //初始信用分
		accountCreditLogDO.setChangeValue(creditValue);
		accountCreditLogDO.setCreateTime(new Date());
		accountCreditLogDAO.insert(accountCreditLogDO);
		
		UserPointDO userPoint = new UserPointDO();
		userPoint.setUserId(userInfoDO.getId());
		userPoint.setPointValue(100);
		userPoint.setCreateTime(new Date());
		userPointDAO.save(userPoint);
		UserPointLogDO userPointLog = new UserPointLogDO();
		userPointLog.setChangeType(30);
		userPointLog.setChangeValue(100);
		userPointLog.setPointId(userPoint.getId());
		userPointLog.setCreateTime(new Date());
		userPointLogDAO.save(userPointLog);
		String gift = null ;
		if(null != register_gift) {
			gift = register_gift;
		}else {
			gift = "20.00";
		}
		AccountCashDO accountCash = new AccountCashDO();
		AccountCashLogDO accountCashLog = new AccountCashLogDO();
		accountCash.setCashAmount(new BigDecimal(gift));
		accountCashLog.setChangeAmount(new BigDecimal(gift));
		
		if(!ObjectUtils.isEmpty(visitorIdStr)) {
			Long visitorUserId = getUserId(visitorIdStr);
			if(null != visitorUserId) {
				UserInfoDO visitorDO = userInfoDAO.get(visitorUserId);
				if(null == visitorDO) {
					logger.info("根据vistorId[{}]，查询不到用户，故不加费用");
				}else {
					AccountCashDO visitorAccountCash = accountCashDAO.getByUserid(visitorDO.getId());
					String inviteAmount = configInfoManager.getValue("invite_amount");
					visitorAccountCash.setCashAmount(visitorAccountCash.getCashAmount().add(new BigDecimal(inviteAmount)));
					visitorAccountCash.setModifyTime(new Date());
					accountCashDAO.update(visitorAccountCash);
					AccountCashLogDO visitorAccountCashLog = new AccountCashLogDO();
					visitorAccountCashLog.setAccountCashId(visitorAccountCash.getId());
					visitorAccountCashLog.setChangeAmount(new BigDecimal(inviteAmount));
					visitorAccountCashLog.setChargeType(BizConstants.ACCOUNT_CASH_CHARGE_TYPE_80);
					visitorAccountCashLog.setOperType(BizConstants.ACCOUNT_CASH_OPER_TYPE_10);
					visitorAccountCashLog.setCreateTime(new Date());
					accountCashLogDAO.insert(visitorAccountCashLog);
					UserInviterRelationDO relation = new UserInviterRelationDO();
					relation.setCreateTime(new Date());
					relation.setGiveAmount(new BigDecimal(inviteAmount));
					relation.setInviterUserId(visitorDO.getId());
					relation.setInviteeUserId(userInfoDO.getId());
					userInviterRelationDAO.insert(relation);
					flag = 1;
					
					//微信推送
					wxAPPMessagePushService.sendMerchantActivityNotice(visitorDO.getId(), "￥"+visitorAccountCashLog.getChangeAmount(), null);
					wxAPPMessagePushService.sendMerchantActivityNotice(userInfoDO.getId(), "￥"+accountCash.getCashAmount(), null);
				}
			}
		}
		accountCash.setUserId(userInfoDO.getId());
		accountCash.setDepositAmount(new BigDecimal(0.00));
		accountCash.setStatus(BizConstants.ACCOUNT_CASH_STATUS_10);
		accountCash.setCreateTime(new Date());
		accountCashDAO.insert(accountCash);
		
		
		accountCashLog.setAccountCashId(accountCash.getId());
		
		accountCashLog.setOperType(BizConstants.ACCOUNT_CASH_OPER_TYPE_10);
		accountCashLog.setChargeType(BizConstants.ACCOUNT_CASH_CHARGE_TYPE_30);	
		accountCashLog.setCreateTime(new Date());
		accountCashLogDAO.insert(accountCashLog);
		
		UserCostFlagDO costFlagDO = new UserCostFlagDO();
		costFlagDO.setUserId(userInfoDO.getId());
		costFlagDO.setFlag(BizConstants.USER_COST_FLAG_FLAG_1);
		BigDecimal price = new BigDecimal(configInfoManager.getValue("cost_per_book_per_day"));
		costFlagDO.setRemainder(new BigDecimal(gift));
		costFlagDO.setPrice(price);
		costFlagDO.setCostOrder(BizConstants.USER_COST_FLAG_COSTORDER_1);
		costFlagDO.setCreateTime(new Date());
		costFlagDO.setValidFlag(BizConstants.USER_COST_FLAG_VALIDFLAG_1);
		userCostFlagDAO.insert(costFlagDO);
		
		//记录用户登陆/注册 log表
		UserAccessLogDO accessLogDO = new UserAccessLogDO();
		accessLogDO.setUserId(userInfoDO.getId());
		accessLogDO.setLoginIp(accessLog.getIp());
		accessLogDO.setPartner(accessLog.getPartner());
		accessLogDO.setLogType(BizConstants.USER_ACCESS_LOG_TYPE_0);
		accessLogDO.setOperTime(new Date());
		userAccessLogDAO.insert(accessLogDO);
		UserEntiretyDTO userEntiretyDTO = new UserEntiretyDTO();
		userEntiretyDTO.setWish_list_count(0);
		
		userEntiretyDTO.setUserid(userInfoDO.getId());
		userEntiretyDTO.setBorrowed_count(0);
		userEntiretyDTO.setBorrowing_count(0);
		userEntiretyDTO.setCash_amount(new BigDecimal(gift).toString());
		userEntiretyDTO.setCredit_value(creditValue);
		userEntiretyDTO.setDeposit_amount(new BigDecimal(0.00));
		userEntiretyDTO.setCost(new BigDecimal(0.00));
		userEntiretyDTO.setUsertoken(usertoken);
		userEntiretyDTO.setTobe_deposit_amount(new BigDecimal(deposit_amount));
		userEntiretyDTO.setStatus("0");
		userEntiretyDTO.setIntegration(100l);
		userEntiretyDTO.setRank("");
		userEntiretyDTO.setVip_content("");
		userEntiretyDTO.setVip_type("0");
		String visitorUrl = getVisitorUrl(userInfoDO.getId());
		userEntiretyDTO.setVisitor_url(configInfoManager.getImgUrlPrefix() + visitorUrl);
		UserEntiretyDO userEntiretyDO = new UserEntiretyDO();
		userEntiretyDO.setBorrowedCount(0);
		userEntiretyDO.setBorrowingCount(0);
		userEntiretyDO.setCashAmount(gift);
		userEntiretyDO.setCost("0.00");
		userEntiretyDO.setCreditValue(creditValue);
		userEntiretyDO.setDepositAmount("0.00");
		userEntiretyDO.setTobeDepositAmount(deposit_amount);
		userEntiretyDO.setUserId(userInfoDO.getId());
		userEntiretyDO.setIntegration(100l);
		userEntiretyDAO.insert(userEntiretyDO);
		userEntiretyDTO.setInviteFlag(flag);
		resp.setBody(userEntiretyDTO);
		
		//登录如果有unionid，判断是否更新
		try {
			logger.info("login更新unionid对应wxuserRelation");
			setUserinfoUnionidNull(recordDTO, userInfoDO.getId());
			intersystemCommunicationManager.publishEvent(userInfoDO.getId(), EventEnum.REGIST);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return resp;
		
	}
	
	
	public  VenusSvcResp<UserEntiretyDTO> loginWithoutVerifaction(String registrationId,String visitorIdStr, 
			String mobile,UserAccessLogDTO accessLog, String wxUserRelationId) throws BizException {
		//查询unionid
		String unionid = null;
		WxUserRelationDO record = new WxUserRelationDO();
		WxUserRelationDTO recordDTO = new WxUserRelationDTO();
		if(!ObjectUtils.isEmpty(wxUserRelationId)) {
			record.setId(wxUserRelationId);
			record = wxUserRelationDAO.getInfoById(record);//找到wx_user_relation数据，后续update userid
			if(!ObjectUtils.isEmpty(record)) {
				unionid = record.getUnionid();
				BeanUtils.copyProperties(record, recordDTO);
			}
		}
		
		VenusSvcResp<UserEntiretyDTO> resp = new VenusSvcResp<UserEntiretyDTO>();
				//总的需要缴纳押金金额
				String deposit_amount = configInfoManager.getValue("deposit_amount");
				String init_credit_value = configInfoManager.getValue("init_credit_value");
				String register_gift = configInfoManager.getValue("register_gift");
				//2.判断该手机号是否已经注册,若未注册,则直接注册,并返回
				UserEntiretyDTO userEntiretyDTO = new UserEntiretyDTO();
				
				boolean isNew = isNewUser(mobile);
				int flag = -1;
				if(isNew) {
					//未注册,则直接进行注册,并返回对象
					return registerNewUser(mobile, registrationId, visitorIdStr, accessLog, recordDTO, deposit_amount, init_credit_value, register_gift);
				}
				UserInfoDO userInfoDO = userInfoDAO.getByMobileNo(mobile);
				//活动请求，只判断是否存在注册,如果存在不再改变token
				if("h5Activity".equals(accessLog.getPartner())) {
					return resp;
				}
				
				String usertoken = MD5Util.generateToken();
				
				if(!ObjectUtils.isEmpty(visitorIdStr)) {
					Long visitorUserId = getUserId(visitorIdStr);
					if(null != visitorUserId) {
						UserInfoDO visitorDO = userInfoDAO.get(visitorUserId);
						if(null != visitorDO) {
							flag = 0;
						}
					}
				}		
				//3.组装返回参数
				
				//=============添加user_token信息=============//
				UserTokenDO userTokenDO = new UserTokenDO();
				Byte channel = BizConstants.CHANNEL_APP;
				if(!ObjectUtils.isEmpty(accessLog.getPartner()) && accessLog.getPartner().equals("wx_app")) {
					channel = BizConstants.CHANNEL_WX;
				}
				userTokenDO.setChannel(channel);
				userTokenDO.setUserId(userInfoDO.getId());
				userTokenDO.setToken(usertoken);
				if(userTokenDAO.selectByUserIdAndChannel(userTokenDO) != null) {
					userTokenDAO.updateByUserIdAndChannel(userTokenDO);
				}else {
					userTokenDO.setId(UUID.randomUUID().toString().replace("-", ""));
					userTokenDAO.insert(userTokenDO);
				}
				//=============添加user_token end================//
				
				userInfoDO.setUsertoken(userTokenDO.getToken());
				userInfoDO.setNewUsertoken(null);
				userInfoDO.setTokenExpireTimes(null);
				userInfoDO.setTokenGenerateTime(new Date());
				userInfoDO.setRegistrationId(registrationId);
				userInfoDAO.update(userInfoDO);
				
				//记录用户登陆/注册 log表
				UserAccessLogDO accessLogDO = new UserAccessLogDO();
				accessLogDO.setUserId(userInfoDO.getId());
				accessLogDO.setLoginIp(accessLog.getIp());
				accessLogDO.setPartner(accessLog.getPartner());
				accessLogDO.setLogType(BizConstants.USER_ACCESS_LOG_TYPE_1);
				accessLogDO.setOperTime(new Date());
				userAccessLogDAO.insert(accessLogDO);
				
				userEntiretyDTO.setUserid(userInfoDO.getId());
				userEntiretyDTO.setUsername(userInfoDO.getUserName());
				userEntiretyDTO.setImgurl(configInfoManager.getImgurl(userInfoDO.getImgurl()));
				userEntiretyDTO.setUsertoken(usertoken);
				userEntiretyDTO.setStatus(userInfoDO.getStatus()+"");
				//2.1查询押金,余额
				AccountCashDO accountCashDO = accountCashDAO.getByUserid(userInfoDO.getId());
				if(accountCashDO == null) {
					userEntiretyDTO.setCash_amount(new BigDecimal(0.00).toString());
					userEntiretyDTO.setDeposit_amount(new BigDecimal(0.00));
					userEntiretyDTO.setTobe_deposit_amount(new BigDecimal(deposit_amount));
				}else {
					userEntiretyDTO.setCash_amount(accountCashDO.getCashAmount().setScale(2, RoundingMode.HALF_UP).toString());
					userEntiretyDTO.setDeposit_amount(accountCashDO.getDepositAmount().setScale(2, RoundingMode.HALF_UP));
					userEntiretyDTO.setTobe_deposit_amount(new BigDecimal(deposit_amount));
				}
				//2.2查询信用分
				AccountCreditDO accountCreditDO = accountCreditDAO.getByUserid(userInfoDO.getId());
				userEntiretyDTO.setCredit_value(accountCreditDO.getCreditValue());
				
				//2.3获得用户已借阅总数 ,用户在借阅总数,用户目前再借最长天数
				int borrowedCount = orderTransDAO.getBorrowedCount(userInfoDO.getId());
				int borrowingCount = orderTransDAO.getBorrowingCount(userInfoDO.getId());
				int day = orderTransDAO.getLongestBorrowDay(userInfoDO.getId());
				
				BigDecimal cost = bookgridService.getCostByUser(userInfoDO.getId());
				if(null == cost) {
					cost = new BigDecimal(0.00);
				}
				userEntiretyDTO.setBorrowed_count(borrowedCount);
				userEntiretyDTO.setBorrowing_count(borrowingCount);
				userEntiretyDTO.setLongest_borrowing_day(day);
				userEntiretyDTO.setCost(cost);
				BookGridTransDO queryDO = new BookGridTransDO();
				queryDO.setUserId(userInfoDO.getId());
				queryDO.setPresentDate(new Date());
				List<BookGridTransDO> bookGridTransList = bookGridTransDAO.getLockStatusByUser(queryDO);
				if(CollectionUtils.isEmpty(bookGridTransList)) {
					userEntiretyDTO.setGrid_code("");
					userEntiretyDTO.setGrid_status(BizConstants.GRID_LOCK_STATUS_5);
				}else {	//如果不为空，则说明有请求打开、或者已打开的书格
					BookGridTransDO first = bookGridTransList.get(0);
					userEntiretyDTO.setGrid_code(first.getGridCode());
					userEntiretyDTO.setGrid_status(first.getLockStatus());
					int remainseconds = bookgridService.queryRemainingSeconds(first.getGridCode(), userInfoDO.getId());
					userEntiretyDTO.setRemainseconds(remainseconds);
					
				}
				UserPointDO userPoint = userPointDAO.getByUserId(userInfoDO.getId());
				if(null == userPoint) {
					userEntiretyDTO.setIntegration(100l);
					UserPointDO p = new UserPointDO();
					p.setUserId(userInfoDO.getId());
					p.setPointValue(100);
					p.setCreateTime(new Date());
					userPointDAO.save(p);
					UserPointLogDO userPointLog = new UserPointLogDO();
					userPointLog.setChangeType(30);
					userPointLog.setChangeValue(100);
					userPointLog.setPointId(p.getId());
					userPointLog.setCreateTime(new Date());
					userPointLogDAO.save(userPointLog);
				}else {
					UserPointLogDO userPointLog = new UserPointLogDO();
					userPointLog.setChangeType(41);
					userPointLog.setChangeValue(5);
					userPointLog.setPointId(userPoint.getId());
					userPointLog.setCreateTime(new Date());
					userPointLogDAO.save(userPointLog);
					userPoint.setPointValue(userPoint.getPointValue()+5);
					userPoint.setModifyTime(new Date());
					userPointDAO.update(userPoint);
					Integer point = userPoint.getPointValue();
					userEntiretyDTO.setIntegration(Long.valueOf(point));
				}
				String rank = getPersonRank(userInfoDO.getId());
				if(null == rank) {
					rank = "";
				}
				userEntiretyDTO.setRank(rank);
				userEntiretyDTO.setVip_content("暂未开通会员");
				userEntiretyDTO.setVip_type("0");
				Date expireDate = null ;
				VipMemberDO vipMember = vipMemberDAO.getByUserId(userInfoDO.getId());
				if(null != vipMember) {
					expireDate = vipMember.getEndTime();
				}
				if(expireDate != null){
					if(new Date().compareTo(DateFormatUtil.getMaxTimeDay(expireDate)) > 0) {	//如果当前日期大于过期日期，则说明该月卡已失效
						VipMemberDO vmQuery = new VipMemberDO();
						vmQuery.setUserId(userInfoDO.getId());
						VipMemberDO result = vipMemberDAO.getByCondition(vmQuery );
						result.setValidFlag(0);
						result.setModifyTime(new Date());
						vipMemberDAO.update(result);
					}else {
						userEntiretyDTO.setVip_content("剩余" + DateFormatUtil.getDays(new Date(), DateFormatUtil.getMaxTimeDay(expireDate)) + "天");
						userEntiretyDTO.setVip_type(vipMember.getVipType()+"");
					}
				}
				String visitorUrl = getVisitorUrl(userInfoDO.getId());
				userEntiretyDTO.setVisitor_url(configInfoManager.getImgUrlPrefix() + visitorUrl);
				userEntiretyDTO.setInviteFlag(flag);
				int wishCount = userWishListDAO.countWishListByUser(userInfoDO.getId());
				userEntiretyDTO.setWish_list_count(wishCount);
				resp.setBody(userEntiretyDTO);
				
				//登录如果有unionid，判断是否更新
				try {
						//删掉之前的unionid
						setUserinfoUnionidNull(recordDTO, userInfoDO.getId());
				}catch (Exception e) {
					e.printStackTrace();
				}
				intersystemCommunicationManager.publishEvent(userInfoDO.getId(), EventEnum.LOGIN);
				return resp;
	}

	public void setUserinfoUnionidNull(WxUserRelationDTO recordDTO, Long userid) {
		
		if(!ObjectUtils.isEmpty(recordDTO) && !ObjectUtils.isEmpty(userid)) {
			logger.info("login setUserinfoUnionidNull wxUserRelation id{},userid{}",recordDTO.getId(),userid);
			String unionid = recordDTO.getUnionid();
			WxUserRelationDO record = new WxUserRelationDO();
			BeanUtils.copyProperties(recordDTO, record);
			//根据unionid查询userinfo，删除之前关联的unionid信息，新增当前userid和unionid之间的信息
			if(!ObjectUtils.isEmpty(unionid) && !"null".equals(unionid) &&!ObjectUtils.isEmpty(userid)) {
				UserInfoDO userinfoDo = new UserInfoDO();
				userinfoDo.setUnionid(unionid);
				List<UserInfoDO> userinfoDos = userInfoDAO.getUserinfoByUnionid(userinfoDo);
				userinfoDo.setModifyTime(new Date());
				if(!ObjectUtils.isEmpty(userinfoDos) && userinfoDos.size() > 0) {
					//设置之前的unionid为null
					userInfoDAO.updateUnionidNullByIdOrUnionid(userinfoDo);
				}
				//更新对应unionid值
				userinfoDo.setId(userid);
				userInfoDAO.updateUnionidById(userinfoDo);
			}
			//更新wx_user_relation表数据，删除之前userid关联的信息，新增当前的关联
			record.setUserId(userid);
			//清掉之前的userid
			wxUserRelationDAO.updateUseridNullByUserid(record);
			//重新建立userid的关系
			wxUserRelationDAO.updateById(record);
		}
		
	}
	
	private String getVisitorUrl(Long userId) {
		UserAttachmentInfoDO query = new UserAttachmentInfoDO();
		query.setUserId(userId);
		query.setAttaType("01");
		UserAttachmentInfoDO userAtta01 = userAttachmentInfoDAO.getByCondition(query);
		if(userAtta01 == null) {
			userAtta01 = new UserAttachmentInfoDO();
			userAtta01.setUserId(userId);
			userAtta01.setAttaType("01");
			String encrypt = "";
			//1.获取二维码生成内容以及图片路径
			String encrypt_key = configInfoManager.getValue("qecode_encrpyt_key");
			try {
				encrypt = DesUtils.encrypt(userId+"", encrypt_key);
			} catch (Exception e1) {
				logger.error("生成邀请二维码异常", e1);
				encrypt = userId+"";
			}
			String text = configInfoManager.getValue("qrcode_prefix");
			text += ("visitorId="+encrypt);
			String visitorImgPathPrefix = configInfoManager.getValue("visitor_img_path");
			String iconPath = visitorImgPathPrefix + "icon.png";
			String visitorBgPath = visitorImgPathPrefix + "visitor_bg.png";
			DateFormat df = new SimpleDateFormat("yyyyMM");
			String suffix = System.currentTimeMillis() + getRandom() + ".jpg"; 
			String fileName = "qrcode_" + suffix;
			String visitorName = "visitor_" + suffix;
			String qrcodePath = visitorImgPathPrefix + df.format(new Date()) + File.separator + fileName;
			String visitorPath = visitorImgPathPrefix + df.format(new Date()) + File.separator + visitorName;
			try {
				//2.生成二维码图片
				QRCodeUtil.encode(text, iconPath, qrcodePath);
				//3.生成邀请图片
				ImageMergeUtil.merge(visitorBgPath, qrcodePath, visitorPath);
				//4.上传到OSS服务器中
				String key = "visitor_imgs/" + df.format(new Date()) + "/" + visitorName;
				ossUploadManager.uploadImg(new File(visitorPath), key);
				
				//5.保存到数据库中
				userAtta01.setAttaContent("/" + key);
				userAtta01.setCreateTime(new Date());
				userAttachmentInfoDAO.save(userAtta01);
				return "/" + key;
			} catch (Exception e) {
				logger.error("生成二维码失败", e);
			}
		}
		return userAtta01.getAttaContent();
	}
	@Override
	public VenusSvcResp<UserLastestInfoDTO> getUserInfo(UserQueryDTO userQuery)  throws BizException{
		
		VenusSvcResp<UserLastestInfoDTO> resp = new VenusSvcResp<UserLastestInfoDTO>();
		resp.setRspCode(0);
		UserLastestInfoDTO info = new UserLastestInfoDTO();
		
		Long userid = userQuery.getUserid();

		//1.获取用户相关信息
		UserInfoDO userInfoDO = userInfoDAO.get(userid);
		if(userInfoDO == null) {
			resp = new VenusSvcResp<>(RspCodeEnum.USER_NOT_FOUND);
			return resp ;
		}
		//1.1 如果数据库中存在new_usertoken，则直接使用新的usertoken 来代替原来的usertoken,传递给前端
		if(!ObjectUtils.isEmpty(userInfoDO.getNewUsertoken())) {
			info.setUsertoken(userInfoDO.getNewUsertoken());
		}
		//1.2设置积分
		UserPointDO userPoint = userPointDAO.getByUserId(userid);
		if(userPoint == null) {
			userPoint = new UserPointDO();
			userPoint.setUserId(userid);
			userPoint.setPointValue(100);
			userPoint.setCreateTime(new Date());
			userPointDAO.save(userPoint);
			info.setIntegration(100l);
			UserPointLogDO userPointLog = new UserPointLogDO();
			userPointLog.setChangeType(30);
			userPointLog.setChangeValue(100);
			userPointLog.setPointId(userPoint.getId());
			userPointLog.setCreateTime(new Date());
			userPointLogDAO.save(userPointLog);
		}else {
			info.setIntegration(Long.valueOf(userPoint.getPointValue()));
		}
		//2 设置相关参数
		info.setUserid(userid);
		info.setUsername(userInfoDO.getUserName());
		info.setImgurl(configInfoManager.getImgurl(userInfoDO.getImgurl()));
		info.setStatus(userInfoDO.getStatus()+"");
		info.setMobile_no(userInfoDO.getMobileNo());
		//2.1查询押金,余额
		//总的需要缴纳押金金额
		String deposit_amount = configInfoManager.getValue("deposit_amount");
		AccountCashDO accountCashDO = accountCashDAO.getByUserid(userid);
		if(accountCashDO == null) {
			info.setCash_amount(new BigDecimal(0.00).toString());
			info.setDeposit_amount(new BigDecimal(0.00));
			info.setTobe_deposit_amount(new BigDecimal(deposit_amount));
		}else {
			info.setCash_amount(accountCashDO.getCashAmount().setScale(2, RoundingMode.HALF_UP).toString());
			info.setDeposit_amount(accountCashDO.getDepositAmount().setScale(2, RoundingMode.HALF_UP));
			info.setTobe_deposit_amount(new BigDecimal(deposit_amount));
		}
		//2.2查询信用分
		AccountCreditDO accountCreditDO = accountCreditDAO.getByUserid(userid);
		info.setCredit_value(accountCreditDO.getCreditValue());
		//2.3获得用户已借阅总数 ,用户在借阅总数,用户目前再借最长天数
		int borrowedCount = orderTransDAO.getBorrowedCount(userInfoDO.getId());
		int borrowingCount = orderTransDAO.getBorrowingCount(userInfoDO.getId());
		int day = orderTransDAO.getLongestBorrowDay(userInfoDO.getId());
		BigDecimal cost = bookgridService.getCostByUser(userInfoDO.getId());
		if(null == cost) {
			cost = new BigDecimal(0.00);
		}
		info.setCost(cost);
		info.setBorrowed_count(borrowedCount);
		info.setBorrowing_count(borrowingCount);
		info.setLongest_borrowing_day(day);
		//2.4 获取用户当前是否有开柜，或者请求开柜的动作
		BookGridTransDO queryDO = new BookGridTransDO();
		queryDO.setUserId(userid);
		queryDO.setPresentDate(new Date());
		queryDO.setLockStatus(BizConstants.GRID_LOCK_STATUS_1);
		List<BookGridTransDO> bookGridTransList = bookGridTransDAO.getLockStatusByUser(queryDO);
		if(CollectionUtils.isEmpty(bookGridTransList)) {
			info.setGrid_code("");
			info.setGrid_status(3);
		}else {	//如果不为空，则说明有请求打开、或者已打开的书格
			BookGridTransDO first = bookGridTransList.get(0);
			info.setGrid_code(first.getGridCode());
			info.setGrid_status(first.getLockStatus());
			int remainseconds = bookgridService.queryRemainingSeconds(first.getGridCode(), userid);
			info.setRemainseconds(remainseconds);
			
		}
		info.setVip_content("暂未开通会员");
		info.setVip_type("0");
		Date expireDate = null ;
		VipMemberDO vipMember = vipMemberDAO.getByUserId(userInfoDO.getId());
		if(null != vipMember) {
			expireDate = vipMember.getEndTime();
		}
		if(expireDate != null){
			if(new Date().compareTo(DateFormatUtil.getMaxTimeDay(expireDate)) > 0) {	//如果当前日期大于过期日期，则说明该月卡已失效
				VipMemberDO vmQuery = new VipMemberDO();
				vmQuery.setUserId(userInfoDO.getId());
				VipMemberDO result = vipMemberDAO.getByCondition(vmQuery );
				result.setValidFlag(0);
				result.setModifyTime(new Date());
				vipMemberDAO.update(result);
			}else {
				info.setVip_content("剩余" + DateFormatUtil.getDays(new Date(), DateFormatUtil.getMaxTimeDay(expireDate)) + "天");
				info.setVip_type(vipMember.getVipType()+"");
			}
		}
		
		String visitorUrl = getVisitorUrl(userInfoDO.getId());
		info.setVisitor_url(configInfoManager.getImgUrlPrefix() + visitorUrl);
		String rank = getPersonRank(userid);
		info.setRank(rank);
		int wishCount = userWishListDAO.countWishListByUser(userInfoDO.getId());
		info.setWish_list_count(wishCount);
		resp.setBody(info);
		return resp;
	}

	@Override
	public UserInfoDTO get(Long userId)  throws BizException{
		
		UserInfoDO info = userInfoDAO.get(userId);
		if(info == null)
			throw new BizException(RspCodeEnum.USER_NOT_FOUND) ;
		info.setImgurl(configInfoManager.getImgurl(info.getImgurl()));
		UserInfoDTO userInfoDTO = new UserInfoDTO();
		BeanUtils.copyProperties(info, userInfoDTO);
		return userInfoDTO;
	}

	
	
	@Override
	public int update(UserInfoDTO infoDTO) throws BizException {
		String imgurl = infoDTO.getImgurl();
		String imgurlPrefix = configInfoManager.getImgUrlPrefix();
		if(imgurl.startsWith(imgurlPrefix)) {
			int len = imgurlPrefix.length();
			int lastPos = imgurl.lastIndexOf("?");
			if(-1 == lastPos) {
				lastPos = imgurl.length();
			}
			imgurl = imgurl.substring(len, lastPos);
		}
		UserInfoDO userInfo = new UserInfoDO();
		BeanUtils.copyProperties(infoDTO, userInfo);
		userInfo.setImgurl(imgurl);
		return userInfoDAO.update(userInfo);
	}

	@Override
	public void reportAbnormal(ReportAbnormalDTO reportAbnormalDTO)  throws BizException{
	
		Long userid = reportAbnormalDTO.getUserid();
		String describe = reportAbnormalDTO.getDescribe();
		Integer maintainType = reportAbnormalDTO.getMaintain_type();
		BookGridTransDO result = bookGridTransDAO.getLastestGridCodeByUser(userid);
		if(result == null)
			return ;
		String grid_code = result.getGridCode();
		
		GridMaintainLogDO query = new GridMaintainLogDO();
		query.setUserId(userid);
		if(30 == maintainType){			//盘点报修
			query.setBookgridCode(grid_code);
			query.setMaintainType(30);
			int reportCount = gridMaintainLogDAO.countByGridCodeAndUser(query);
			int limitCount = Integer.valueOf(configInfoManager.getValue("report_error_count"));
			if(reportCount > limitCount) {
				throw new BizException(RspCodeEnum.BOOK_GRID_CANNOT_BE_REPORTED);
			}
		}else if(20 == maintainType){	//倒计时报修
			String shelfCode = bookGridDAO.get(grid_code).getBookshelfCode();
			query.setBookgridCode(shelfCode);
			query.setMaintainType(20);
			int reportCount = gridMaintainLogDAO.countByShelfCodeAndUser(query);
			if(reportCount >= 1){
				throw new BizException(RspCodeEnum.BOOK_SHELF_HAS_BEAN_REPORTED);
			}
		}
		int count = gridMaintainLogDAO.countByGridCode(grid_code);
		BookGridDO bookGrid = bookGridDAO.get(result.getGridCode());
		Integer lockStatus = bookGrid.getLockStatus();
		//1.更新书格信息状态:damage_report =1(报修)  如果同一个书格报修三次，则直接damage_report=2
		if(count >= 2) {
			bookGrid.setDamageReport(2);
		}else {
			bookGrid.setDamageReport(1);
		}
		if(BizConstants.GRID_LOCK_STATUS_0 == lockStatus || BizConstants.GRID_LOCK_STATUS_2 == lockStatus) {
			bookGrid.setLockStatus(BizConstants.GRID_LOCK_STATUS_5);
			result.setLockStatus(BizConstants.GRID_LOCK_STATUS_5);
			
		}else if(BizConstants.GRID_LOCK_STATUS_1 == lockStatus) {
			bookGrid.setLockStatus(BizConstants.GRID_LOCK_STATUS_3);
			result.setLockStatus(BizConstants.GRID_LOCK_STATUS_3);
		}
		bookGrid.setModifyTime(new Date());
		bookGridDAO.update(bookGrid);
		result.setModifyTime(new Date());
		bookGridTransDAO.update(result);
		//2.插入书格报修表
		GridMaintainLogDO maintainLogDO = new GridMaintainLogDO();
		String[] arr = reportAbnormalDTO.getImgUrlArr();
		if(arr != null && arr.length != 0) {
			String imgUrl = "";
			for(int i=0; i<arr.length; i++) {
				imgUrl += (arr[i]+",");
			}
			imgUrl = imgUrl.endsWith(",") ? imgUrl.substring(0, imgUrl.length()-1) : imgUrl;
			maintainLogDO.setImgUrl(imgUrl);
		}
		maintainLogDO.setBookgridCode(grid_code);
		maintainLogDO.setCreateTime(new Date());
		maintainLogDO.setDescription(describe);
		maintainLogDO.setUserId(userid);
		maintainLogDO.setMaintainCode(reportAbnormalDTO.getCode());
		maintainLogDO.setMaintainStatus("0");
		maintainLogDO.setMaintainType(maintainType);
		gridMaintainLogDAO.insert(maintainLogDO);
		
		//-------------插入报警信息start----------------------
		BsAlarmDTO bsAlarm = new BsAlarmDTO();
		bsAlarm.setBookgridCode(grid_code);
		bsAlarm.setAlarmType(BizConstants.BS_ALARM_TYPE_8);
		String alarmContent = "";
		if(20 == maintainType) {
			alarmContent = "书格["+grid_code+"]在倒计时页面发生异常。";
		}else if(30 == maintainType) {
			alarmContent = "书格["+grid_code+"]在借阅成功页面发生异常。";
		}
		bsAlarm.setAlarmContent(alarmContent);
		bsAlarmService.saveBsAlarm(bsAlarm);
		//-------------插入报警信息end----------------------
	}

	@Override
	public BorrowingBookDTO getBorrowingList(Long userid)  throws BizException{
		BorrowingBookDTO borrowingBookDTO = new BorrowingBookDTO();
		
		List<GridCodeAndBorrowDateDO> list = orderTransDAO.getGridCodeByUser(userid);
		if(CollectionUtils.isEmpty(list))
			return null ;
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		int totalcount = 0;
		for(int i=0; i<list.size(); i++) {
			GridCodeAndBorrowDateDO gridCodeDO = list.get(i);
			BorrowingBook borrowingBook = new BorrowingBook();
			borrowingBook.setBorrow_date(df.format(gridCodeDO.getBorrowDate()));
			totalcount += gridCodeDO.getGridCodeCount();
			borrowingBook.setBorrowcount(gridCodeDO.getGridCodeCount());
			borrowingBook.setGrid_code(gridCodeDO.getGridCode());
			borrowingBook.setSerialnumber(gridCodeDO.getGridCode().substring(10));
			borrowingBook.setShelf_code(gridCodeDO.getGridCode().substring(0, 10));
			
			List<BorrowingBookDO> bookList = orderTransDAO.getBorrowingList(new BorrowingBookQueryDO(userid, gridCodeDO.getGridCode()));
			if(!CollectionUtils.isEmpty(bookList)) {
				for(BorrowingBookDO borrowingBookDO : bookList) {
					BRBookDTO brbook = new BRBookDTO();
					brbook.setBookname(borrowingBookDO.getBookName());
					brbook.setIsbn(borrowingBookDO.getIsbn());
					brbook.setImgurl(configInfoManager.getImgurl(borrowingBookDO.getImgurl()));
					borrowingBook.getBooks().add(brbook);
				}
			}
			
			borrowingBookDTO.getBorrowlist().add(borrowingBook);
		}
		borrowingBookDTO.setTotalcount(totalcount);
		return borrowingBookDTO;
	}

	@Override
	public boolean isLocked(Long userid) throws BizException{
		
		UserInfoDO userInfo = userInfoDAO.get(userid);
		return 1 == userInfo.getStatus() ;
	}

	@Override
	public int getBorrowingCount(Long userid) throws BizException {
		return orderTransDAO.getBorrowingCount(userid);
	}

	@Override
	public boolean isInCurrentGrid(Long userid, String gridCode)  throws BizException{
		
		List<GridCodeAndBorrowDateDO> list = orderTransDAO.getGridCodeByUser(userid);
		for(GridCodeAndBorrowDateDO borrowBook : list) {
			if(borrowBook.getGridCode().equals(gridCode)) {
				return true ;
			}
		}
		return false;
	}

	@Override
	public void feedback(ReportAbnormalDTO reportAbnormalDTO)  throws BizException{
		
		String describe = reportAbnormalDTO.getDescribe();
		Long userid = reportAbnormalDTO.getUserid();
		UserFeedbackDO userFeedbackDO = new UserFeedbackDO();
		userFeedbackDO.setUserId(userid);
		userFeedbackDO.setContent(describe);
		userFeedbackDO.setCreateTime(new Date());
		userFeedbackDO.setType(11);//暂定11为意见反馈
		userFeedbackDO.setTopic("用户反馈");
		userFeedbackDAO.insert(userFeedbackDO);
	}

	@Override
	public void logout(UserAccessLogDTO accessLog)  throws BizException{
		//1.记录到 用户登陆流水表中
		UserAccessLogDO accessLogDO = new UserAccessLogDO();
		accessLogDO.setLoginIp(accessLog.getIp());
		accessLogDO.setLogType(BizConstants.USER_ACCESS_LOG_TYPE_2);
		accessLogDO.setOperTime(new Date());
		accessLogDO.setPartner(accessLog.getPartner());
		accessLogDO.setUserId(accessLog.getUserid());
		userAccessLogDAO.insert(accessLogDO);
		
		//2.更新用户信息的token为null
		UserInfoDO userInfo = userInfoDAO.get(accessLog.getUserid());
		if(null == userInfo)
			return ;
		userInfo.setUsertoken(null);
		userInfo.setNewUsertoken(null);
		userInfo.setTokenExpireTimes(null);
		userInfo.setTokenGenerateTime(null);
		userInfoDAO.update(userInfo);
	}

	@Override
	public VenusSvcResp<String> equipActive(UserActiveDTO activeDTO)  throws BizException{
		logger.info("equipActive's {}", JSON.toJSONString(activeDTO));
		VenusSvcResp<String> resp = new VenusSvcResp<String>();
		
		Integer dataver = activeDTO.getDataver();
		logger.info("dataver: {}" , dataver);
		String data = activeDTO.getData();
		if(1 != dataver)
			return null ;
		try {
			Map<String, Object> map = decrypt(data);
			check(map);
			String guid = (String) map.get("guid");
			if(ObjectUtils.isEmpty(guid)) {
				guid =  MD5Util.generateGuid();
				insertToEquipment(guid, map);
			}else {
				UserEquipmentDO userEquipment = userEquipmentDAO.getByGuid(guid);
				if(null != userEquipment) {
					userEquipment.setDevicetoken((String)map.get("devicetoken"));
					userEquipment.setPushstatus((Integer)map.get("pushstatus"));
					userEquipment.setUuid((String)map.get("uuid"));
					userEquipmentDAO.update(userEquipment);
				}else {
					guid = MD5Util.generateGuid();
					insertToEquipment(guid, map);
				}
			}
			resp.setBody(guid);
			
			insertToTrace(guid,map);
		} catch (Exception e) {
			if(e instanceof BizException) {
				resp.setRspCodeEnum(((BizException) e).getRspCodeEnum());
			}else {
				resp.setRspCodeEnum(RspCodeEnum.CODE_SYS_ERROR);
			}
		}
		
		return resp ;
	}
	private void check(Map<String, Object> map) throws BizException {
		
		Integer device_type = (Integer) map.get("device_type");
		RspCodeEnum rsp = RspCodeEnum.PARAM_CHECK_IS_NULL ;
		if(ObjectUtils.isEmpty(device_type)) {
			rsp.setRspMessage("device_type");
			throw new BizException(rsp);
		}
		String device = (String) map.get("device");
		if(ObjectUtils.isEmpty(device)) {
			rsp.setRspMessage("device");
			throw new BizException(rsp);
		}
		String os = (String) map.get("os");
		if(ObjectUtils.isEmpty(os)) {
			rsp.setRspMessage("os");
			throw new BizException(rsp);
		}
		String network = (String) map.get("network");
		if(ObjectUtils.isEmpty(network)) {
			rsp.setRspMessage("network");
			throw new BizException(rsp);
		}
		String package_name = (String) map.get("package_name");
		if(ObjectUtils.isEmpty(package_name)) {
			rsp.setRspMessage("package_name");
			throw new BizException(rsp);
		}
		
		String app_version = (String) map.get("app_version");
		if(ObjectUtils.isEmpty(app_version)) {
			rsp.setRspMessage("app_version");
			throw new BizException(rsp);
		}
		
		String active_time = (String) map.get("active_time");
		if(ObjectUtils.isEmpty(active_time)) {
			rsp.setRspMessage("active_time");
			throw new BizException(rsp);
		}
		
		String uuid = (String) map.get("uuid");
		if(ObjectUtils.isEmpty(uuid)) {
			rsp.setRspMessage("uuid");
			throw new BizException(rsp);
		}
		Integer pushstatus = (Integer) map.get("pushstatus");
		if(ObjectUtils.isEmpty(pushstatus)) {
			rsp.setRspMessage("pushstatus");
			throw new BizException(rsp);
		}
		//安卓
		if(0 == device_type) {
			String partner = (String) map.get("partner");
			if(ObjectUtils.isEmpty(partner)) {
				rsp.setRspMessage("partner");
				throw new BizException(rsp);
			}
		}
	}

	private void insertToTrace(String guid, Map<String, Object> map) {
		
		UserActivetraceDO activeTraceDO = new UserActivetraceDO();
		activeTraceDO.setActiveTime(DateFormatUtil.parseDateTime((String)map.get("active_time")));
		activeTraceDO.setAndroidDeviceid((String)map.get("android_deviceid"));
		activeTraceDO.setAppVersion((String)map.get("app_version"));
		activeTraceDO.setCreateTime(DateUtil.now());
		activeTraceDO.setDevice((String)map.get("device"));
		activeTraceDO.setGuid((String)map.get("guid"));
		activeTraceDO.setIdfa((String)map.get("idfa"));
		activeTraceDO.setImsiNo((String)map.get("imsi_no"));
		activeTraceDO.setMacAddress((String)map.get("mac_address"));
		activeTraceDO.setNetwork((String)map.get("network"));
		activeTraceDO.setOs((String)map.get("os"));
		activeTraceDO.setPackageName((String)map.get("package_name"));
		activeTraceDO.setPartner((String)map.get("partner"));
		activeTraceDO.setSimNo((String)map.get("sim_no"));
		activeTraceDO.setUuid((String)map.get("uuid"));
		
		activeTraceDO.setDevicetoken((String)map.get("devicetoken"));
		activeTraceDO.setPushstatus((Integer)(map.get("pushstatus")));
		activeTraceDO.setDeviceType((Integer)(map.get("device_type")));
		
		userActivetraceDAO.insert(activeTraceDO);		
		
	}

	private void insertToEquipment(String guid, Map<String, Object> map) {
		UserEquipmentDO userEquipment = new UserEquipmentDO();
		
		userEquipment.setDevicetoken((String)map.get("devicetoken"));
		userEquipment.setPushstatus(Integer.parseInt(map.get("pushstatus")+""));
		userEquipment.setUuid((String)map.get("uuid"));
		userEquipment.setGuid(guid);
		userEquipment.setCreateTime(new Date());
		
		userEquipmentDAO.insert(userEquipment);
	}

	/**
	 * 设备激活 解密方法
	 * @param data
	 * @return
	 * @throws BizException 
	 */
	private Map<String, Object> decrypt(String data) throws BizException {
		//TODO 解密
		Map map = new HashMap();
		try {
			String decryptedData = WdbEncrypt.decrypt(data);
			Object obj = JSON.parse(decryptedData);
			if(obj instanceof JSONObject) {
				map = (Map<String, Object>) obj;
			}else if(obj instanceof JSONArray) {
				throw new BizException(RspCodeEnum.ACTIVE_DATA_IS_ARRAY);
			}
		} catch (WdbEncryptException e) {
			logger.error(e.getMessage(), e);
			throw new BizException(RspCodeEnum.ACTIVE_DATA_IS_INVALID);
		}
		return map;
	}
	
	@Override
	public String equipActiveStatus(UserActiveDTO activeDTO)  throws BizException{
		logger.info("equipActiveStatus {}", JSON.toJSONString(activeDTO));
		Integer dataver = activeDTO.getDataver();
		String data = activeDTO.getData();
		logger.info("dataver: {}" , dataver);
		if(1 != dataver)
			return null ;
		try {
			Map<String, Object> map = decrypt(data);
			check(map);
			String devicetoken = (String)map.get("devicetoken");
			Integer pushstatus = (Integer)(map.get("pushstatus"));
			UserEquipmentDO userEquipment = userEquipmentDAO.getByDeviceToken(devicetoken);
			if(userEquipment == null) {
				return null ;
			}
			userEquipment.setPushstatus(pushstatus);
			userEquipmentDAO.update(userEquipment);
			return userEquipment.getGuid();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		
		return null ;
	}

	@Override
	public WishListPageResultDTO queryWishList(WishListPageQueryDTO pageQueryDTO) throws BizException {
		
		WishInfoPageQueryDO pageQueryDO = new WishInfoPageQueryDO();
		BeanUtils.copyProperties(pageQueryDTO, pageQueryDO);
		logger.info("oper: " + pageQueryDO.getOper());
		int count = userWishListDAO.countWishList(pageQueryDO);
		List<WishInfoDO> list = userWishListDAO.getWishList(pageQueryDO);
		
		WishListPageResultDTO result = new WishListPageResultDTO();
		result.setTotalcount(count);
		
		if(CollectionUtils.isEmpty(list))
			throw new BizException(RspCodeEnum.QUERY_LIST_IS_NULL);
		for(WishInfoDO info : list) {
			WishListDTO dto = new WishListDTO();
			BeanUtils.copyProperties(info, dto);
			dto.setBookname(info.getBookName());
			dto.setImgurl(configInfoManager.getImgurl(info.getImgurl()));
			Integer stored = info.getStored();
			Integer status = info.getStatus();
			if(1 == status) {
				dto.setStatus(0);
			}else if(2 == status) {
				dto.setStatus(3);
			}else if(0 == stored){
				dto.setStatus(2);
			}else {
				dto.setStatus(1);
			}
			dto.setBorrow_count(info.getBorrowCount());
			result.getWishList().add(dto);
		}
		return result;
	}

	
	@Override
	public List<WishListResultDTO> queryWishListV2(WishListPageQueryDTO pageQueryDTO) throws BizException {
		WishInfoPageQueryDO pageQueryDO = new WishInfoPageQueryDO();
		pageQueryDO.setShelfCode(pageQueryDTO.getShelfCode());
		pageQueryDO.setUserid(pageQueryDTO.getUserid());
		List<WishInfoDO> list = userWishListDAO.getWishListV2(pageQueryDO);
		if(CollectionUtils.isEmpty(list))
			throw new BizException(RspCodeEnum.QUERY_LIST_IS_NULL);
		Set<Long> idSet = new HashSet<Long>();
		List<WishListResultDTO> resultList = new ArrayList<WishListResultDTO>();
		Map<String, List<WishListDTO>> map = new LinkedHashMap<String, List<WishListDTO>>();
		for(WishInfoDO info : list) {
			if("zanque".equals(info.getGridCode())) {
				if(idSet.contains(info.getId())) {
					continue;
				}
			}else {
				idSet.add(info.getId());
			}
			WishListDTO dto = new WishListDTO();
			
			BeanUtils.copyProperties(info, dto);
			dto.setBookname(info.getBookName());
			dto.setImgurl(configInfoManager.getImgurl3(info.getImgurl()));
			Integer status = info.getStatus();
			if(1 == status || 2 == status) {
				dto.setStatus(0);
			}else {
				dto.setStatus(1);
			}
			if(!map.containsKey(info.getGridCode())) {
				map.put(info.getGridCode(), new ArrayList<WishListDTO>());
			}
			List<WishListDTO> wl = map.get(info.getGridCode());
			wl.add(dto);
		}
		Set<String> keySets = map.keySet();
		for(String gridCode: keySets) {
			WishListResultDTO resultDTO = new WishListResultDTO();
			resultDTO.setGrid_code(gridCode);
			resultDTO.setWishList(map.get(gridCode));
			resultList.add(resultDTO);
		}
		return resultList;
	}


	@Override
	public void removeWishBook(Long id, Long userId, String isbn) throws BizException {
		if(null != id) {
			UserWishListDO condition = new UserWishListDO();
			condition.setId(id);
			condition.setDelFlag(1);
			condition.setModifyTime(new Date());
			userWishListDAO.update(condition);
		}else if(!ObjectUtils.isEmpty(isbn)){
			UserWishListDO condition = new UserWishListDO();
			condition.setIsbn(isbn);
			condition.setUserId(userId);
			
			List<UserWishListDO> result = userWishListDAO.getByIsbn(condition);
			if(null == result || result.size() == 0) {
				throw new BizException(RspCodeEnum.OBJ_NOT_FOUND.setRspMessage("心愿单"));
			}
			for(UserWishListDO wish : result) {
				wish.setDelFlag(1);
				wish.setModifyTime(new Date());
				userWishListDAO.update(wish);
			}
		}else {
			throw new BizException(RspCodeEnum.ISBN_AND_IS_BOTH_NULL);
		}
		
	}

	@Override
	public void saveWishBook(Long userId, String isbn) throws BizException {
		
		UserWishListDO userWishBookDO = new UserWishListDO();
		userWishBookDO.setCreateTime(new Date());
		userWishBookDO.setIsbn(isbn);
		userWishBookDO.setUserId(userId);
		userWishBookDO.setStatus(0);
		userWishBookDO.setDelFlag(0);
		UserWishListDO result = userWishListDAO.getByCondition(userWishBookDO);
		if(result != null)
			return ;
		userWishListDAO.insert(userWishBookDO);
		
	}

	@Override
	public int getIsbnWishFlag(String isbn, Long userId) throws BizException {
		
		UserWishListDO condition = new UserWishListDO();
		condition.setIsbn(isbn);
		condition.setUserId(userId);
		List<UserWishListDO> wish = userWishListDAO.getByIsbn(condition);
		
		return null == wish || wish.size() == 0 ? 0 : 1;
	}

	@Override
	public RankListPageResultDTO queryRankList(RankListPageQueryDTO pageQueryDTO,Long userId) throws BizException {

		UserRankInfoPageQueryDO pageQueryDO = new UserRankInfoPageQueryDO();
		BeanUtils.copyProperties(pageQueryDTO, pageQueryDO);
		logger.info("oper: " + pageQueryDO.getOper());
		RankListPageResultDTO result = new RankListPageResultDTO();
		int count = 0;
		List<UserRankInfoDO> list = new ArrayList<UserRankInfoDO>();
		if("0".equals(pageQueryDTO.getOper().trim())) {//首次请求
			count = userInfoDAO.countRankList2();
			list = userInfoDAO.getUserRankList(pageQueryDO);
		}else {
			//首先获取用户所属小区
			String shelfCode = userInfoDAO.getUserShelfCode(userId);
			if(shelfCode==null||"".equals(shelfCode.trim())) {
				result.setTotalcount(count);
				return result;
			}
			pageQueryDO.setShelfCode(shelfCode);
			count = userInfoDAO.countUserRankByArea(shelfCode);
			list = userInfoDAO.getAreaRankList(pageQueryDO);
		}
		if(CollectionUtils.isEmpty(list))
			throw new BizException(RspCodeEnum.QUERY_LIST_IS_NULL);
		for(UserRankInfoDO info:list) {
			UserRankDTO dto = new UserRankDTO();
			dto.setArea(info.getArea());
			dto.setImgurl(configInfoManager.getImgurl(info.getImgurl()));
			dto.setRank_num(info.getRownum());
			dto.setBook_count(info.getBookCount());
			dto.setCumulative_time("0");
			dto.setUser_name(info.getUserName());
			result.getRankList().add(dto);
		}
		result.setTotalcount(count);
		return result;
	}

	@Override
	public UserRankDTO queryUserRank(RankListPageQueryDTO pageQueryDTO,Long userId) throws BizException {
		UserRankInfoPageQueryDO pageQueryDO = new UserRankInfoPageQueryDO();
		BeanUtils.copyProperties(pageQueryDTO, pageQueryDO);
		pageQueryDO.setUserid(userId);
		logger.info("oper: " + pageQueryDO.getOper());
		UserRankDTO result = new UserRankDTO();
		int count = 0;
		UserRankInfoDO mark = null;
		if("0".equals(pageQueryDTO.getOper().trim())) {//全国排名
			mark = userInfoDAO.gerUserRankAllInfo(userId);//获取用户在全国的排名
			count = userInfoDAO.countAllUserRank();
			result.setImgurl(configInfoManager.getImgurl(mark.getImgurl()));
			result.setUser_name(mark.getUserName());
		}else {
			//首先获取用户所属小区
			String shelfCode = userInfoDAO.getUserShelfCode(userId);
			if(shelfCode==null||"".equals(shelfCode.trim())) {
				UserInfoDO userInfoDO = userInfoDAO.get(userId);
				result.setBook_count(0);
				result.setUser_name(userInfoDO.getUserName());
				result.setCumulative_time("0");
				result.setImgurl(configInfoManager.getImgurl(userInfoDO.getImgurl()));
				result.setRank_num(0l);
				result.setRank_percentage("0.00%");
				return result;
			}
			pageQueryDO.setShelfCode(shelfCode);
			pageQueryDO.setUserid(userId);
			mark = userInfoDAO.getUserRankAreaInfo(pageQueryDO);//查询用户在借书最多的小区的排名,能查到书柜就有排名
			count = userInfoDAO.countUserRankByArea(shelfCode);
			result.setImgurl(configInfoManager.getImgurl(mark.getImgurl()));
			result.setUser_name(mark.getUserName());
		}
		BigDecimal countBig = new BigDecimal(count);
		if(mark.getRownum()==null) {
			result.setBook_count(0);
			result.setCumulative_time("0");
			result.setRank_num(0l);
			result.setRank_percentage("0.00%");
		}else {
			BigDecimal markBig = new BigDecimal(count-mark.getRownum());
			BigDecimal bigRankPer = markBig.divide(countBig,4,BigDecimal.ROUND_DOWN);
			DecimalFormat df3 = new DecimalFormat("##0.00%");
			
			result.setCumulative_time("0");
			result.setRank_num(mark.getRownum());
			result.setRank_percentage(df3.format(bigRankPer));
			result.setBook_count(mark.getBookCount());
		}
		return result;
	}

	@Override
	public UserDespositCashStatusDTO queryUserDepositAmount(Long userid) throws BizException {
		
		UserDespositCashStatusDTO statusDTO = new UserDespositCashStatusDTO();
		
		AccountCashDO accountCash = accountCashDAO.getByUserid(userid);
		if(null == accountCash)
			throw new BizException(RspCodeEnum.OBJ_NOT_FOUND.setRspMessage("现金账户"));
		BigDecimal deposit = accountCash.getDepositAmount();
		if(null != deposit && Double.compare(deposit.doubleValue(), 0.00) > 0)
			statusDTO.setDepositStatus(1);
		else {
			statusDTO.setDepositStatus(0);
		}
		BigDecimal cash = accountCash.getCashAmount();
		BigDecimal deafaultCash = new BigDecimal(configInfoManager.getValue("default_opened_account_value"));
		
		if(null != cash && Double.compare(cash.doubleValue(), deafaultCash.doubleValue()) < 0) {
			statusDTO.setCashStatus(0);
		}else {
			statusDTO.setCashStatus(1);
		}
		
		return statusDTO;
	}

	private String getRandom() {
		Random random = new Random();
		String s = "";
		for(int i=0; i<3; i++) {
			s += random.nextInt(10);
		}
		return s;
	}
	
	@Override
	public String uploadUserHead(byte[] imgData) throws BizException {
		
		String imgUrl = null;
		
		String userHeadPrefix = configInfoManager.getValue("user_head_prefix");
		if(null == userHeadPrefix)
			userHeadPrefix = "E:\\var\\venus";
		DateFormat df = new SimpleDateFormat("yyyyMM");
		String yyyyMM = df.format(new Date());
		File dir = new File(userHeadPrefix + File.separator + yyyyMM);
		if(!dir.exists())
			dir.mkdirs();
		
		String newFileName = System.currentTimeMillis() + getRandom() + ".jpeg";
		imgUrl = "user_head/" + yyyyMM + "/" + newFileName;
		
        try {
        	ossUploadManager.uploadUserHead(imgData, imgUrl);
		} catch (Exception e) {
			logger.error("上传用户图片失败", e);
		}
		return   "/" + imgUrl;
	}

	@Override
	public void updateUserInfo(UserInfoDTO infoDTO) throws BizException {
		
		UserInfoDO user = userInfoDAO.get(infoDTO.getId());
		if(user == null)
			throw new BizException(RspCodeEnum.OBJ_NOT_FOUND.setRspMessage("用户"));
		if(infoDTO.getUserName() != null)
			user.setUserName(infoDTO.getUserName());
		if(infoDTO.getImgurl() != null)
			user.setImgurl(infoDTO.getImgurl());
		user.setModifyTime(new Date());
		userInfoDAO.update(user);
	}

	@Override
	public String getPersonRank(Long userId) throws BizException {
		
		Integer rank = userInfoDAO.getPersonRank(userId);
		if(rank != null && rank < 100) {
			return rank+"" ;
		}
		return null;
	}

	@Override
	public DeviceUpgradeFlagDTO getUpgrade(Integer deviceType, String version) throws BizException {
		
		DeviceUpgradeFlagDTO flagDTO = new DeviceUpgradeFlagDTO();
		DeviceVersionDO deviceVersion = deviceVersionDAO.getByType(deviceType);
		if(null == deviceVersion)
			throw new BizException(RspCodeEnum.OBJ_NOT_FOUND.setRspMessage("升级信息"));
		String appVersion = deviceVersion.getAppVersion();
		if(Integer.valueOf(version) < Integer.valueOf(appVersion)) {
			flagDTO.setUpgrade(deviceVersion.getUpgradeFlag());
			flagDTO.setVersionContent(deviceVersion.getVersionContent());
			flagDTO.setDownloadUrl(deviceVersion.getDownloadUrl());
			flagDTO.setMd5Value(deviceVersion.getMd5Value());
		} else {
			flagDTO.setUpgrade(0);
			flagDTO.setMd5Value(deviceVersion.getMd5Value());
			flagDTO.setDownloadUrl(deviceVersion.getDownloadUrl());
		}
		return flagDTO;
	}


	@Override
	public List<UserFamilyMemberDTO> getFamilyMembers(Long userId) throws BizException {
		
		List<UserFamilyMemberDTO> dtoList = new  ArrayList<UserFamilyMemberDTO>();
		List<UserFamilyMemberDO> list = userFamilyMemberDAO.listByUserId(userId);
		for(UserFamilyMemberDO memberDo : list) {
			UserFamilyMemberDTO dto = new UserFamilyMemberDTO();
			memberDo.setImgurl(configInfoManager.getImgurl(memberDo.getImgurl()));
			BeanUtils.copyProperties(memberDo, dto);
			dtoList.add(dto);
		}
		return dtoList;
	}


	@Override
	public void updateUserFamilyMember(UserFamilyMemberDTO dto) throws BizException {
		logger.info("updateUserFamilyMember 请求对象: {}", JSON.toJSONString(dto));
		UserFamilyMemberDO memberDO = userFamilyMemberDAO.get(dto.getId());
		if(null == memberDO)
			throw new BizException(RspCodeEnum.OBJ_NOT_FOUND.setRspMessage("家庭成员"));
		if(!dto.getUserId().equals(memberDO.getUserId()))
			throw new BizException(RspCodeEnum.USER_IS_NOT_SUITED);
		if(0 == dto.getMemberType()) {
			UserInfoDO userInfo = userInfoDAO.get(dto.getUserId());
			if(dto.getImgurl() != null) {
				userInfo.setImgurl(dto.getImgurl());
			}
			if(dto.getUserName() != null) {
				userInfo.setUserName(dto.getUserName());
			}
			if(dto.getMobileNo() != null) {
				userInfo.setMobileNo(dto.getMobileNo());
			}
			userInfo.setModifyTime(new Date());
			userInfoDAO.update(userInfo);
		}
		if(dto.getImgurl() != null) {
			memberDO.setImgurl(dto.getImgurl());
		}
		if(dto.getUserName() != null) {
			memberDO.setUserName(dto.getUserName());
		}
		if(dto.getGender() != null) {
			memberDO.setGender(dto.getGender());
		}
		if(dto.getBirth() != null) {
			memberDO.setBirth(dto.getBirth());
		}
		if(dto.getMobileNo() != null) {
			memberDO.setMobileNo(dto.getMobileNo());
		}
		if(dto.getMemberName() != null) {
			memberDO.setMemberName(dto.getMemberName());
		}
		if(dto.getMemberType() != null) {
			memberDO.setMemberType(dto.getMemberType());
		}
		memberDO.setModifyTime(new Date());
		
		if(0 == dto.getMemberType() && memberDO.getBirth() != null && memberDO.getGender() != null && memberDO.getImgurl() != null && memberDO.getMemberName() != null && memberDO.getMemberType() != null && memberDO.getMobileNo() != null && memberDO.getUserName() != null) {
			UserPointDO userPoint = userPointDAO.getByUserId(dto.getUserId());
			if(null != userPoint) {
				UserPointLogDO query = new UserPointLogDO();
				query.setPointId(userPoint.getId());
				query.setChangeType(44);
				int count = userPointLogDAO.countByCondition(query);
				if(count == 0) {
					userPoint.setModifyTime(new Date());
					userPoint.setPointValue(userPoint.getPointValue()+50);
					userPointDAO.update(userPoint);
					
					UserPointLogDO userPointLog = new UserPointLogDO();
					userPointLog.setChangeType(44);
					userPointLog.setChangeValue(50);
					userPointLog.setCreateTime(new Date());
					userPointLog.setPointId(userPoint.getId());
					userPointLogDAO.save(userPointLog);
				}
			}
			
		}
		userFamilyMemberDAO.update(memberDO);
	}


	@Override
	public void addUserFamilyMember(UserFamilyMemberDTO dto) throws BizException {
		UserFamilyMemberDO memberDO = new UserFamilyMemberDO();
		BeanUtils.copyProperties(dto, memberDO);
		memberDO.setCreateTime(new Date());
		userFamilyMemberDAO.save(memberDO);
	}


	@Override
	public String aesDecrypt(String bookcaseId) throws BizException {
		try {
			QrCodePoliciesLogDO currentInfoDO = qrCodePoliciesLogDAO.getByShortKey(bookcaseId);
			if(null == currentInfoDO) {
				throw new RuntimeException("根据二维码[" + bookcaseId + "]从数据库中查询不到二维码生成信息");
			}
			String shelfCode = currentInfoDO.getBookcaseId();
			BookShelfDO bookShelf = bookShelfDAO.get(shelfCode);
			if(null == bookShelf) {
				throw new RuntimeException("根据二维码[" + bookcaseId + "]从数据库中查询的书柜编号["+shelfCode+"]不存在书柜信息");
			}
			Date generateTime = currentInfoDO.getGenerateTime();
			Date now = new Date();
			if(now.compareTo(generateTime) > 1000 * 60 * 10) {
				throw new RuntimeException("根据二维码["+bookcaseId+"]从数据库中查询出来的生成时间["+generateTime+"] 距离服务器时间超过5分钟");
			}
			return shelfCode;
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new BizException(RspCodeEnum.QRCODE_ANALYSIS_IS_WRONG);
		}
	}
	
	private Long getUserId(String encrypt) {
		String key = configInfoManager.getValue("qecode_encrpyt_key");
		try {
			String decrypt = DesUtils.decrypt(encrypt, key);
			return Long.valueOf(decrypt);
		} catch (Exception e) {
			logger.error("邀请好友二维码解析异常", e);
		}
		return null ;
	}


	@Override
	public String getUserVIPEndDate(String mobile_no) throws BizException {
		
		UserInfoDO userInfo = userInfoDAO.getByMobileNo(mobile_no);
		if(null == userInfo) {
			throw new BizException(RspCodeEnum.OBJ_NOT_FOUND.setRspMessage("用户"));
		}
		Long userId = userInfo.getId();
		VipMemberDO vipMember = vipMemberDAO.getByUserId(userId);
		if(null == vipMember) {
			return "";
		}
		Date endTime = vipMember.getEndTime();
		return DateFormatUtil.formatDate(endTime);
	}


	@Override
	public VenusSvcResp<UserLastestInfoDTO> getUserInfoByWx(String openid, String appid) throws BizException {
		WxUserRelationDO query = new WxUserRelationDO();
		query.setOpenid(openid);
		query.setAppId(appid);
		List<WxUserRelationDO> list = wxUserRelationDAO.listByCondition(query);
		if(list == null) {
			throw new BizException(RspCodeEnum.OBJ_NOT_FOUND.setRspMessage("用户"));
		}
		Long userid = list.get(0).getUserId();
		if(null == userid) {
			throw new BizException(RspCodeEnum.OBJ_NOT_FOUND.setRspMessage("用户"));
		}
		
		UserQueryDTO userQuery = new UserQueryDTO();
		userQuery.setUserid(userid);
		return getUserInfo(userQuery );
	}


	@Override
	public String getUserInfo(String mobileNo) throws BizException {
		UserInfoDO userInfo = userInfoDAO.getByMobileNo(mobileNo);
		if(null == userInfo) {
			throw new BizException(RspCodeEnum.OBJ_NOT_FOUND.setRspMessage("用户"));
		}
		return userInfo.getId()+"";
	}
	
	@Override
	public String getTokenByChannelAndUserId(Long userId, Byte channel) throws BizException {
		UserTokenDO query = new UserTokenDO();
		query.setUserId(userId);
		query.setChannel(channel);
		UserTokenDO	userTokenDO	= userTokenDAO.selectByUserIdAndChannel(query);
		if(userTokenDO != null) {
			return userTokenDO.getToken();
		}
		return null;
	}


	@Override
	public UserInviteInfoDTO getInviteInfo(Long userId) throws BizException {
		
		UserInviteInfoDTO inviteInfo = new UserInviteInfoDTO();
		
		int inviteCount = userInviterRelationDAO.count(userId);
		
		UserAttachmentInfoDO query = new UserAttachmentInfoDO();
		query.setUserId(userId);
		query.setAttaType("01");
		UserAttachmentInfoDO info = userAttachmentInfoDAO.getByCondition(query);
		String inviteUrl = "";
		if(null != info) {
			inviteUrl = configInfoManager.getImgUrlPrefix() + info.getAttaContent();
		}
		BigDecimal bonus = userInviterRelationDAO.getBonus(userId);
		String bonusStr = "0.00";
		if(null != bonus) {
			bonusStr = bonus.doubleValue()+"";
		}
		inviteInfo.setBonus(bonusStr);
		inviteInfo.setInviteCount(inviteCount);
		inviteInfo.setInviteUrl(inviteUrl);
		return inviteInfo;
	}


	@Override
	public List<WeekRankInfoDTO> queryWeekRankList() throws BizException {
		List<WeekReadRankDO> list = userReadStatisticsDAO.getWeekReadRankList();
		if(CollectionUtils.isEmpty(list))
			throw new BizException(RspCodeEnum.QUERY_LIST_IS_NULL);
		List<WeekRankInfoDTO> dtoList = new ArrayList<WeekRankInfoDTO>();
		for(WeekReadRankDO wrrDO : list) {
			WeekRankInfoDTO dto = new WeekRankInfoDTO();
			dto.setBook_count(wrrDO.getWeek_count());
			if(null != wrrDO.getWeek_cumulative_time()) {
				dto.setCumulative_time(wrrDO.getWeek_cumulative_time().doubleValue()+"");
			}
			
			if(!ObjectUtils.isEmpty(wrrDO.getNick_name())) {
				dto.setUser_name(wrrDO.getNick_name());
				dto.setImgurl(wrrDO.getAvatar_url());
			}else {
				dto.setUser_name(wrrDO.getUser_name());
				dto.setImgurl(configInfoManager.getImgurl(wrrDO.getImgurl()));
			}
			dtoList.add(dto);
		}
		return dtoList;
	}


	@Override
	public WeekRankInfoDTO queryPersonInWeekRank(Long userId) throws BizException {
		
		WeekRankInfoDTO dto = new WeekRankInfoDTO();
		
		UserReadStatisticsDO ursDO = userReadStatisticsDAO.getByUserId(userId);
		UserReadStatisticsDO totalRecord = userReadStatisticsDAO.getUserTotalRecordFromOrderTrans(userId);
		UserReadStatisticsDO monthRecord = userReadStatisticsDAO.getUserMonthRecordFromOrderTrans(userId);
		UserReadStatisticsDO weekRecord = userReadStatisticsDAO.getUserWeekRecordFromOrderTrans(userId);
		if(null == ursDO && totalRecord != null) {
			if(null != weekRecord) {
				totalRecord.setWeekCount(weekRecord.getWeekCount());
				totalRecord.setWeekCumulativeTime(weekRecord.getWeekCumulativeTime());
			}
			if(null != monthRecord) {
				totalRecord.setMonthCount(monthRecord.getMonthCount());
				totalRecord.setMonthCumulativeTime(monthRecord.getMonthCumulativeTime());
			}
			
			totalRecord.setUserId(userId);
			totalRecord.setId(UUID.randomUUID().toString().replaceAll("-", ""));
			totalRecord.setCreateTime(new Date());
			userReadStatisticsDAO.insert(totalRecord);
		}else if(null != ursDO && totalRecord != null) {
			ursDO.setTotalCount(totalRecord.getTotalCount());
			ursDO.setTotalCumulativeTime(totalRecord.getTotalCumulativeTime());
			if(null != weekRecord) {
				ursDO.setWeekCount(weekRecord.getWeekCount());
				ursDO.setWeekCumulativeTime(weekRecord.getWeekCumulativeTime());
			}
			if(null != monthRecord) {
				ursDO.setMonthCount(monthRecord.getMonthCount());
				ursDO.setMonthCumulativeTime(monthRecord.getMonthCumulativeTime());
			}
			ursDO.setModifyTime(new Date());
			userReadStatisticsDAO.update(ursDO);
		}else if(null != ursDO && totalRecord == null){
			ursDO.setTotalCount(0);
			ursDO.setTotalCumulativeTime(new BigDecimal("0.00"));
			ursDO.setWeekCount(0);
			ursDO.setWeekCumulativeTime(new BigDecimal("0.00"));
			ursDO.setMonthCount(0);
			ursDO.setMonthCumulativeTime(new BigDecimal("0.00"));
			ursDO.setModifyTime(new Date());
			userReadStatisticsDAO.update(ursDO);
		}else{	//用户从来没有发生过借阅行为
			dto.setBook_count(0);
			dto.setCumulative_time("0.00");
			dto.setRank_percentage("0.00%");
			
			int count = userReadStatisticsDAO.count();
			WeekReadRankDO wrrDO = userReadStatisticsDAO.getUserInfo(userId);
			dto.setRank(count+1);
			if(!ObjectUtils.isEmpty(wrrDO.getNick_name())) {
				dto.setUser_name(wrrDO.getNick_name());
				dto.setImgurl(wrrDO.getAvatar_url());
			}else {
				dto.setUser_name(wrrDO.getUser_name());
				dto.setImgurl(configInfoManager.getImgurl(wrrDO.getImgurl()));
			}
			return dto;
		}
		
		//计算排名
		WeekReadRankDO wrrDO = userReadStatisticsDAO.getPersonInWeekRank(userId);
		int count = userReadStatisticsDAO.count();
		dto.setRank(wrrDO.getRank());
		dto.setBook_count(wrrDO.getWeek_count());
		if(null != wrrDO.getWeek_cumulative_time()) {
			dto.setCumulative_time(wrrDO.getWeek_cumulative_time().doubleValue()+"");
		}
		if(!ObjectUtils.isEmpty(wrrDO.getNick_name())) {
			dto.setUser_name(wrrDO.getNick_name());
			dto.setImgurl(wrrDO.getAvatar_url());
		}else {
			dto.setUser_name(wrrDO.getUser_name());
			dto.setImgurl(configInfoManager.getImgurl(wrrDO.getImgurl()));
		}
		BigDecimal countBig = new BigDecimal(count);
		BigDecimal markBig = new BigDecimal(count-wrrDO.getRank());
		BigDecimal bigRankPer = markBig.divide(countBig,4,BigDecimal.ROUND_DOWN);
		DecimalFormat df3 = new DecimalFormat("##0.00%");
		dto.setRank_percentage(df3.format(bigRankPer));
		return dto;
	}
	
	//阅读称号
	public Map<String, Object> readTitleMappingName(Integer readCount) {
		ReadTitleMappingDO readTitleMappingDO = readTitleMappingDAO.selectByReadCount(readCount);
		Map<String, Object> result = new HashMap<>();
			if(!ObjectUtils.isEmpty(readTitleMappingDO)) {
				result.put("title", readTitleMappingDO.getTitle());
				result.put("maxRead", readTitleMappingDO.getMaxRead());
			}
		
		return result;
	}
	public Map<String, Object> selectCurrentTitleByRead(Integer maxRead) {
		ReadTitleMappingDO readTitleMappingDO = readTitleMappingDAO.selectCurrentTitleByRead(maxRead);
		Map<String, Object> result = new HashMap<>();
		if(!ObjectUtils.isEmpty(readTitleMappingDO)) {
			result.put("title", readTitleMappingDO.getTitleSource());
			result.put("readCount", readTitleMappingDO.getReadCount());
		}
		return result;
	}
	
	@Override
	public List<UserInfoAndOpenIdDTO> getUserinfoByUnionids(String unionids) {
		if(ObjectUtils.isEmpty(unionids)) {
			return null;
		}
		String[] unionidArray = unionids.split(",");
		List<UserInfoDO> infos = new ArrayList<>();
		if(unionidArray.length < 2) {//单个unionid
			UserInfoDO userinfoDo = new UserInfoDO();
			userinfoDo.setUnionid(unionids);
			
			infos = userInfoDAO.getUserinfoByUnionid(userinfoDo);
			if(ObjectUtils.isEmpty(unionids)) {
				return null;
			}
		}else {//多个unionid
			Map<String, Object> map = new HashMap<>();
			map.put("unionid", Arrays.asList(unionidArray));
			infos = userInfoDAO.getUserinfoByUnionids(map);
		}
		
		List<UserInfoAndOpenIdDTO> dtos = new ArrayList<>();
		for(UserInfoDO info:infos) {
			UserInfoAndOpenIdDTO userInfoDTO = new UserInfoAndOpenIdDTO();
			if(!ObjectUtils.isEmpty(info.getUnionid()) ) {
				//查询unionid对应的头像
				WxUserRelationDO queryWxUserinfo = new WxUserRelationDO();
				queryWxUserinfo.setUnionid(info.getUnionid());
				List<WxUserRelationDO> dos =  wxUserRelationDAO.listByCondition(queryWxUserinfo) ;
				BeanUtils.copyProperties(info, userInfoDTO);
				if(!ObjectUtils.isEmpty(dos)) {
					WxUserRelationDO wxUserinfo = dos.get(0);
					if(wxUserinfo.getAvatarUrl() != null) {
						userInfoDTO.setImgurl(wxUserinfo.getAvatarUrl());
						userInfoDTO.setUserName(wxUserinfo.getNickName());
						userInfoDTO.setOpenid(wxUserinfo.getOpenid());
					}
				}
			}
			
			dtos.add(userInfoDTO);
		}
		return dtos;
	}


	@Override
	public String getMobile(String usertoken) {
		String mobileNo = userInfoDAO.getMobile(usertoken);
		return mobileNo;
	}
	
	public Map<String, Object> getWxUserinfoByTokenV2(String usertoken, Long userId, String appId) {
		Map<String, Object> result = new HashMap<>();
		//根据usertoken查找
		WxUserRelationDO record = new WxUserRelationDO();
		WxUserRelationRpcModel detail = new WxUserRelationRpcModel();
		int newUser = 0;//默认老用户
		String mobile = null;
		UserInfoDO userInfoDO = null;
		if(ObjectUtils.isEmpty(userId)) {
			record.setId(usertoken);
			record = wxUserRelationDAO.getInfoById(record);
			newUser = 1;//没有userid，新用户
		}else {
			record.setUserId(userId);
			record.setAppId(appId);
			userInfoDO = userInfoDAO.get(userId);
			mobile = userInfoDO.getMobileNo();
			List<WxUserRelationDO> records = wxUserRelationDAO.listByCondition(record);
			
			if(!ObjectUtils.isEmpty(records) && records.size() > 0) {
				record = records.get(0);
			}
			AccountCashDO accountCashDO = accountCashDAO.getByUserid(userId);
			//TODO 活动判断新用户逻辑，1是否存在userid，2userid对应是否有押金数据，3判断是否存在押金流水记录
			if(accountCashDO.getDepositAmount() == null || accountCashDO.getDepositAmount().intValue() <= 0) {
				UserChargeLogDO userChargeLogDO= userChargeLogDAO.getDepositByUserId(userId);
				if(ObjectUtils.isEmpty(userChargeLogDO) ) {
					newUser = 1;//新用户
				}
			}
			
		}
		
		if(ObjectUtils.isEmpty(record.getAvatarUrl())) {
			record.setAvatarUrl(configInfoManager.getValue("head_img_default"));
			if(ObjectUtils.isEmpty(userId)) {
				record.setNickName("匿名用户");
			}else {
				record.setNickName(userInfoDO.getUserName());
			}
		}
		BeanUtils.copyProperties(record, detail);
		detail.setNewUser(newUser);
		detail.setMobile(mobile);
		result.put("wxUserRelation", detail);
		return result;
	}


	@Override
	public boolean isNewUser(String mobileNo) {
		
		UserInfoDO userInfo = userInfoDAO.getByMobileNo(mobileNo);
		if(null == userInfo) {
			return true;
		}
		AccountCashDO accountCash = accountCashDAO.getByUserid(userInfo.getId());
		if(null == accountCash) {
			return true;
		}
		return false;
	}


	@Override
	public String zhimaAdmittance(Long userid, String certNo, String realName) throws BizException {
		
		UserInfoDO userInfo = userInfoDAO.get(userid);
		if(null == userInfo)
			throw new BizException(RspCodeEnum.USER_NOT_FOUND);
		userInfo.setCertNo(certNo);
		userInfo.setRealName(realName);
		userInfoDAO.updateCertNoAndRealName(userInfo);
		
		UserZhimaCreditDO zhimaCredit = new UserZhimaCreditDO();
		Integer admittanceScore = Integer.valueOf(configInfoManager.getValue("admittance_score"));
		zhimaCredit.setAdmittanceScore(admittanceScore);
		zhimaCredit.setCertNo(certNo);
		zhimaCredit.setCreateTime(new Date());
		zhimaCredit.setQueryDate(new Date());
		zhimaCredit.setRealName(realName);
		String transactionId = UUID.randomUUID().toString().replaceAll("-", "") + UUID.randomUUID().toString().replaceAll("-", "");
		zhimaCredit.setTransactionId(transactionId);
		zhimaCredit.setUserInfoId(userid);
		userZhimaCreditDAO.insert(zhimaCredit);
		
		Map<String, Object> map = alipayClientManager.ZhimaCreditScoreBriefGet(certNo, transactionId, realName, admittanceScore);
		if(1 == (Integer)map.get("querySuccess")) {
			zhimaCredit.setAdmittanceFlag((String)map.get("admittanceFlag"));
			zhimaCredit.setBizNo((String)map.get("bizNo"));
			userZhimaCreditDAO.update(zhimaCredit);
			return zhimaCredit.getAdmittanceFlag();
		}else if(0 == (Integer)map.get("querySuccess")){
			throw new BizException(RspCodeEnum.CALL_ALIPAY_PARAM_ERROR);
		}else {
			throw new BizException(RspCodeEnum.CALL_ALIPAY_ERROR);
		}
	}
	
}
